package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import bean.Status;
import bean.User;
import dao.UserDao;

/**
 * Servlet implementation class AppLoginServlet
 */
@WebServlet("/AppLoginServlet")
public class AppLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 数据库dao类

		private UserDao userDao = new UserDao();

		protected void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			// 获取用户参数

			String username = request.getParameter("username");
			String password = request.getParameter("password");
			// 将获取到的参数封装到user中

			User u = new User();
			u.setUsername(username);
			u.setPassword(password);
			// 调用dao的用户登录，如果返回null表示用户密码不匹配

			User user = userDao.userLogin(u);
			// 自定义的 状态实体类（包括状态码，详细信息）

			Status status = new Status();
			if (user != null) {// 用户名和密码匹配

				status.setStatusCode("1");
				status.setInfo("恭喜登录成功！");
			} else {
				status.setStatusCode("0");
				status.setInfo("用户名和密码不匹配！");
			}
			// 返回字符串的编码

			response.setContentType("text/html;charset=utf-8");
			// 将status对象作为json发送回客户端

			response.getWriter().print(JSON.toJSON(status));
			;

		}

		protected void doPost(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			doGet(request, response);
		}
}
